package com.mars.component.scheduler.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mars.component.scheduler.constant.SchedulerConst;
import com.mars.component.scheduler.entity.SchedulerJob;
import com.mars.component.scheduler.mapper.SchedulerJobMapper;
import com.mars.component.scheduler.service.SchedulerJobService;
import com.mars.component.scheduler.utlis.SchedulerUtils;
import com.mars.service.support.BaseService;

@Service
public class SchedulerJobServiceImpl extends BaseService<SchedulerJob, Long> implements SchedulerJobService {
	
	@Autowired
	private SchedulerUtils schedulerUtils ;
	
	@Autowired
	private SchedulerJobMapper mapper ;
	
	@Transactional
	@Override
	public void createScheduleJob(SchedulerJob schedulerJob) {
		//保存任务信息到数据库
		super.insertSelective(schedulerJob) ;
		//创建任务
		this.schedulerUtils.createScheduleJob(schedulerJob);
	}
	
	@Transactional
	@Override
	public void rescheduleJob(SchedulerJob schedulerJob) {
		this.schedulerUtils.rescheduleJob(schedulerJob);
		//修改数据库表中的数据
		super.updateSelective(schedulerJob);
	}
	
	@Transactional
	@Override
	public void pauseJob(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			this.schedulerUtils.pauseJob(jobIds[i], groups[i]);
		}
		// 修改数据库表中的状态
		this.mapper.updateBatchStatusByJobId(jobIds, SchedulerConst.ScheduleStatus.PAUSE.getValue());
	}

	@Transactional
	@Override
	public void resumeJob(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			this.schedulerUtils.resumeJob(jobIds[i], groups[i]);
		}
		// 修改数据库表中的状态
		this.mapper.updateBatchStatusByJobId(jobIds, SchedulerConst.ScheduleStatus.NORMAL.getValue());
	}

	@Override
	public void deleteJob(Long[] jobIds, String[] groups) {
		for(int i=0; i<jobIds.length; i++) {
			this.schedulerUtils.deleteJob(jobIds[i], groups[i]);
		}
		// 删除数据库表中的数据
		super.deleteByIds(StringUtils.join(jobIds, ",")) ;
	}

	@Override
	public void runNowJob(Long[] jobIds) {
		for(int i=0; i<jobIds.length; i++) {
			SchedulerJob task = super.selectById(jobIds[i]) ;
			this.schedulerUtils.runNow(task);
		}
	}

}
